<style scoped lang="less">
.page-num {
    line-height: 24px;
    text-align: center;
}
.page-box {
    padding: 0 10px;
    box-sizing: border-box;
}
.null-option {
    padding: 10px 0;
    box-sizing: border-box;
    text-align: center;
}
.operation-btn {
    width: 24px;
    text-align: center;
    padding: 0;
}
.label-box {
    overflow: hidden;
    text-overflow:ellipsis;
    white-space: nowrap;
}
.desc-box{
    color: #999999;
}
.options-item-label{
    flex: none;
    overflow: hidden;
    text-overflow:ellipsis;
    white-space: nowrap;
    padding-right: 3px;
    box-sizing: border-box;
}
.options-item-desc{
    flex: none;
    overflow: hidden;
    text-overflow:ellipsis;
    white-space: nowrap;
    color: #999999;
    box-sizing: border-box;
    padding: 0 3px;
    &:first-child{
        padding: 0 0 0 3px;
    }
    &:last-child{
        padding: 0 0 0 3px;
    }
}
</style>
<template>
    <Select
        ref="select"
        class="ivu-auto-complete"
        :label="label"
        :disabled="disabled"
        :clearable="clearable && !disabled"
        :placeholder="placeholder"
        :size="size"
        :placement="placement"
        v-clickoutside="handleBlur"
        filterable
        remote
        auto-complete
        :remote-method="remoteMethod"
        @on-change="handleChange"
        :transfer="transfer"
        @keydown.tab.native="handleBlur"
        @on-enter="onEnter"
        :options-width="type == 'port' ? '600': '600'"
    >
        <slot name="input">
            <i-input :style="{width:inputWidth}"
                     :element-id="elementId"
                     ref="input"
                     slot="input"
                     v-model="currentValue"
                     :name="name"
                     :placeholder="placeholder"
                     :disabled="disabled"
                     :size="size"
                     :icon="inputIcon"
                     @on-click="handleClear"
                     @on-focus="handleFocus"
            ></i-input>
        </slot>
        <slot>
            <div v-if="!disabled" v-loading="loading" class="no-select of-hidden" @on-select-selected="onSelected" style="background-color: #C2FFC8">
                <i-option v-for="(item, index) in data" :value="item[valueField]" :key="index">
                    <div class="flex" v-if="type == null">
                        <div class="flex-auto label-box" style="width: 350px;">{{ item[labelField] }}</div>
                        <div class="flex-none desc-box" style="width: 200px;" v-if="descField">{{ item[descField] }}</div>
                    </div>
                    <div class="flex" v-else-if="type === 'lease'">
                        <div class="options-item-label" :title="item['leaseCode']" style="width: 150px;">{{ item['leaseCode']!=''?item['leaseCode']:'暂无' }}</div>
                        <div class="options-item-desc" :title="item['leaseStartPortName']" style="width: 150px;">{{ item['leaseStartPortName']!=''?item['leaseStartPortName']:'暂无' }}</div>
                        <div class="options-item-desc" :title="item['leaseTerm']" style="width: 150px;">{{ item['leaseTerm']!=''?item['leaseTerm']:'暂无' }}</div>
                        <div class="options-item-desc" :title="item['remark']" style="width: 150px;">{{ item['remark']!=''?item['remark']:'暂无' }}</div>
                    </div>
                    <div class="flex" v-else-if="type === 'station'">
                        <div class="options-item-label" :title="item['englishName']" style="width: 150px;">{{ item['englishName']!=''?item['englishName']:'暂无' }}</div>
                        <div class="options-item-desc" :title="item['chineseName']" style="width: 150px;">{{ item['chineseName']!=''?item['chineseName']:'暂无' }}</div>
                        <div class="options-item-desc" :title="item['countryName']" style="width: 150px;">{{ item['countryName']!=''?item['countryName']:'暂无' }}</div>
                        <div class="options-item-desc" :title="item['stationCompilation']" style="width: 150px;">{{item['stationCompilation']}}</div>
                    </div>
                    <div class="flex" v-else>
                        <div class="options-item-label" :title="item['code']" style="width: 60px;">{{ item['code'] }}</div>
                        <div class="options-item-desc" :title="item['englishName']" style="width: 150px;">{{ item['englishName']!=''?item['englishName']:'暂无' }}</div>
                        <div class="options-item-desc" :title="item['stateName']" style="width: 120px;">{{ item['stateName']!=''?item['stateName']:'暂无' }}</div>
                        <div class="options-item-desc" :title="item['countryName']" style="width: 120px;">{{item['countryName']!=''?item['countryName']:'暂无' }}</div>
                        <div class="options-item-desc" :title="item['remark']" style="width: 60px;">{{ item['remark']!=''?item['remark']:'暂无' }}</div>
                        <div class="options-item-desc" :title="item['itemOne']" style="width: 50px;">{{ item['itemTwo']!=null?item['itemTwo']:'' }}</div>
                    </div>
                </i-option>
                <div class="null-option" v-if="total === 0" style="width: 550px;">暂无记录</div>
                <div class="flex page-box" v-if="total > pageObj.pageSize" @click.stop>
                    <Button class="flex-none operation-btn" type="default" size="small" :disabled="pageObj.pageNum === 1" @click.native="onPageDbLast()"><Icon type="ios-arrow-back" /></Button>
                    <Button class="flex-none operation-btn" type="default" size="small" :disabled="pageObj.pageNum === 1"  @click.native="onPageLast()"><Icon type="ios-arrow-back" /><Icon type="ios-arrow-back" /></Button>
                    <div class="flex-auto page-num"><span>{{pageObj.pageNum}}</span><span>/</span><span>{{pageCount}}</span></div>
                    <Button class="flex-none operation-btn" type="default" size="small" :disabled="pageObj.pageNum == pageCount" @click.native="onPageNext()"><Icon type="ios-arrow-forward" /></Button>
                    <Button class="flex-none operation-btn" type="default" size="small" :disabled="pageObj.pageNum == pageCount" @click.native="onPageDbNext()"><Icon type="ios-arrow-forward" /><Icon type="ios-arrow-forward" /></Button>
                </div>
            </div>
        </slot>
    </Select>
</template>
<script>
import _ from 'lodash';
export default {
    name: 'select-auto-complete',
    props: {
        value: {
            type: [String, Number],
            default: null
        },
        inputWidth: {
            type: String,
            default: '100%'
        },
        label: {
            type: [String, Number],
            default: ''
        },
        data: {
            type: Array,
            default: () => []
        },
        disabled: {
            type: Boolean,
            default: false
        },
        clearable: {
            type: Boolean,
            default: false
        },
        placeholder: {
            type: String
        },
        size: {
            type: String
        },
        icon: {
            type: String
        },
        filterMethod: {
            type: [Function, Boolean],
            default: false
        },
        placement: {
            type: String,
            default: 'bottom'
        },
        transfer: {
            type: Boolean,
            default: true
        },
        name: {
            type: String
        },
        elementId: {
            type: String
        },
        pageOpt: {
            type: Object,
            default: () => {
                return {
                    pageNum: 1,
                    pageSize: 20,
                    filterList: [],
                    sortList: [],
                    searchKey: ''
                };
            }
        },
        total: {
            type: Number,
            default: 0
        },
        loading: {
            type: Boolean,
            default: false
        },
        labelField: {
            type: String,
            default: null
        },
        valueField: {
            type: String,
            default: 'id'
        },
        descField: {
            type: String,
            default: null
        },
        dataField: {
            type: String,
            default: null
        },
        modelField: {
            type: String,
            default: null
        },
        firstLoadData: {
            type: Boolean,
            default: true
        },
        firstLoadText: {
            type: String,
            default: null
        },
        type: {
            type: String,
            default: null
        }
    },
    data() {
        return {
            currentValue: '',
            disableEmitChange: false, // for Form reset
            pageCount: 0,
            oldValue: null,
            dataObj: {},
            pageObj: _.cloneDeep(this.pageOpt),
            selected: null,
            firstLoaded: false,
            clearFlag: false,
            blurFlag: false,
            netFlag: true
        };
    },
    computed: {
        inputIcon() {
            let icon = '';
            if (this.clearable && this.currentValue) {
                icon = 'ios-close-circle';
            } else if (this.icon) {
                icon = this.icon;
            }
            return icon;
        },
        filteredData() {
            if (this.filterMethod) {
                return this.data.filter(item => this.filterMethod(this.currentValue, item));
            } else {
                return this.data;
            }
        },
        values() {
            return this.value ? [{label: undefined, tag: undefined, value: this.value}] : [];
        }
    },
    created() {
        this.netFlag = this.firstLoadData;
        // console.log('this.firstLoadData:', this.firstLoadData);
        // console.log('this.netFlag:', this.netFlag);
        if (this.value !== '' && this.value !== null) {
            if (!isNaN(Number(this.value))) {
                this.pageObj['customerId'] = Number(this.value);
            }
            if (typeof this.value === 'number') {
                this.pageObj['businessCodeId'] = this.value;
            } else {
                this.pageObj['code'] = this.value;
            }
            if (this.netFlag) {
                this.$emit('on-change', this.pageObj, this.dataField);
            } else {
                this.currentValue = this.firstLoadText;
                // this.selected[this.labelField] = this.firstLoadText;
                this.selected = {};
                this.selected[this.labelField] = this.firstLoadText;
            }
        }
        this.dataListToObj();
        this.debouncedGetFromAPI = _.debounce(this.getFromAPI, 500);
    },
    watch: {
        value(val) {
            // console.log('value-val:', val);
            if (val === null || val === '' || val === undefined) {
                this.currentValue = '';
                this.$refs.select.values = [];
                this.selected = null;
                this.pageObj.pageNum = 1;
                this.clearFlag = false;
                this.handleChange(val);
            } else if ((val !== null && val !== '' && this.selected === null) || (this.selected[this.valueField] !== undefined && val !== this.selected[this.valueField])) { // 1.绑定值不为空,但数据为空(初始化后过程)    2.外部数据变化
                let pageObj = _.cloneDeep(this.pageOpt);
                pageObj.pageNum = 1;
                val
                this.pageObj = pageObj;
                // if (this.netFlag !== null && !this.netFlag){
                //     console.log('111111111');
                //     console.log(this.netFlag);
                this.$emit('on-change', pageObj, this.dataField);
                // }
            }
        },
        currentValue(val) {
            // console.log('currentValue-val:', val);
            this.oldValue = val;
            let _this = this;
            // setTimeout(() => {
            //     if (_this.oldValue === val) {
            //         this.pageObj = _.cloneDeep(this.pageOpt);
            //         this.pageNum = 1;
            //         this.pageObj['searchKey'] = this.currentValue;
            //         if (this.netFlag !== null && this.netFlag) {
            //             _this.$emit('on-change', this.pageObj, this.dataField);
            //         }
            //     }
            // }, 400);
            this.debouncedGetFromAPI();
        },
        total(val) {
            this.pageCount = Math.ceil(val / this.pageObj.pageSize);
        },
        data: {
            handler(val) {
                this.dataListToObj(val);
                if (this.firstLoadData) {
                    if (this.value !== null && this.value !== '' && (this.data.length > 0)) {
                        if (this.dataObj[this.value] !== undefined && this.currentValue !== this.dataObj[this.value][this.labelField]) {
                            this.selected = this.dataObj[this.value];
                            this.currentValue = this.dataObj[this.value][this.labelField];
                            this.$emit('input', this.value);
                            this.$emit('on-select', ((this.value !== null && this.value !== '') ? this.dataObj[this.value] : ''), this.dataField, this.modelField);
                            // this.$refs.select.values = this.values;
                            // this.handleChange(this.value);
                        }
                    }
                }

                this.firstLoaded = true;
                // this.$nextTick(() => {
                //     this.$refs.select.updateDrop();
                // });
            },
            deep: true
        }
    },
    methods: {
        onSelected() {
            this.$refs.select.visible = false;
            this.$refs.input.blur();
        },
        dataListToObj(list) {
            for (let index in list) {
                let item = list[index];
                this.dataObj[item[this.valueField]] = item;
            }
        },
        remoteMethod(query) {
            this.$emit('on-search', query);
        },
        handleChange(val) {
            // console.log("handlechange xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
            if (val !== null && val !== '' && val !== undefined) {
                this.currentValue = this.dataObj[val][this.labelField];
                this.selected = this.dataObj[val];
            }
            // this.$refs.select.values = this.values;
            // this.$refs.input.blur(); // ignore temporary
            this.$emit('input', val);
            this.$emit('on-select', ((val !== null && val !== '' && val !== undefined) ? this.dataObj[val] : ''), this.dataField, this.modelField);
        },
        handleFocus() {
            // console.log("焦点触发");
            // this.netFlag = false;
            this.netFlag = true;
            // console.log('this.value:', this.value);
            if ((this.currentValue == null || this.currentValue == '') || (this.firstLoadData === false)) {
                this.pageObj = _.cloneDeep(this.pageOpt);
                this.pageNum = 1;
                this.pageObj['searchKey'] = this.currentValue;
                this.$emit('on-change', this.pageObj, this.dataField);
            }
            // let _this = this;
            // setTimeout(() => {
            //     _this.$refs.select.visible = true;
            // }, 100);
        },
        handleBlur() {
            // console.log("blur-netflag:", this.netFlag);
            if (this.netFlag) {
                if (this.selected !== null) {
                    this.currentValue = this.selected[this.labelField];
                } else {
                    this.currentValue = '';
                }
            }

            this.$refs.input.blur();
        },
        handleClear() {
            if (!this.clearable) return;
            this.clearFlag = true;
            this.$emit('input', null);
            this.$emit('on-clear', this.dataField);
            this.onFocus();
        },
        onFocus() {
            this.$refs.input.focus();
            this.$nextTick(() => {
                this.handleFocus();
            });
        },
        onPageNext() {
            if (this.pageObj.pageNum < this.pageCount) {
                this.pageObj['searchKey'] = this.currentValue;
                this.pageObj.pageNum = this.pageObj.pageNum + 1;
                this.$emit('on-change', this.pageObj, this.dataField);
            }
        },
        onPageLast() {
            if (this.pageObj.pageNum > 0) {
                this.pageObj['searchKey'] = this.currentValue;
                this.pageObj['pageNum'] = this.pageObj.pageNum - 1;
                this.$emit('on-change', this.pageObj, this.dataField);
            }
        },
        onPageDbNext() {
            this.pageObj['pageNum'] = this.pageCount;
            this.pageObj['searchKey'] = this.currentValue;
            this.$emit('on-change', this.pageObj, this.dataField);
        },
        onPageDbLast() {
            this.pageObj['pageNum'] = 1;
            this.pageObj['searchKey'] = this.currentValue;
            this.$emit('on-change', this.pageObj, this.dataField);
        },
        onEnter() {
            this.handleBlur();
            this.$emit('on-enter', true);
        },
        focus() {
            this.$refs.input.focus();
            this.$nextTick(() => {
                this.handleFocus();
            });
        },
        getFromAPI() {
            this.pageObj = _.cloneDeep(this.pageOpt);
            this.pageNum = 1;
            this.pageObj['searchKey'] = this.currentValue;
            if (this.netFlag !== null && this.netFlag) {
                this.$emit('on-change', this.pageObj, this.dataField);
            }
        }
    }
};
</script>
